package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.WeeklyDateBean;
import com.lzx.iteam.bean.WeeklyDetailListData;
import com.lzx.iteam.bean.WeeklyEditBean;
import com.lzx.iteam.bean.WeeklyTemplate;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.GetWeeklyTemplateMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.util.WeekUtil;
import com.lzx.iteam.widget.MyListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 05月 23日
 * Time: 下午1:46
 *
 * @QQ : 1234567890
 * **********************************
 */
public class WeeklyCreateActivity extends MyBaseActivity implements View.OnClickListener {


    @FindViewById(id = R.id.weekly_cr_tv_time)
    private TextView mTvTime;
    @FindViewById(id = R.id.weekly_cr_lv)
    private MyListView mListView;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.scroll_weekly_cr)
    private ScrollView mLayoutScroll;


//    private int mPosition = -1;
    private int flag;      // 1：创建   2： 编辑
    private boolean mIsOk; //  是否至少填写了一项
    private long mFristDate;
    private String mGroupId;
    private String mTemplateId;
    private String mWeeklyId;

    private Dialog mWaitDialog;
    private List<WeeklyEditBean> mData;
    private WeeklyEditAdapter mAdapter;
    private WeeklyDateBean mSelectDate;
    private WeeklyDetailListData mEditData;

    private static final int SELECT_DATE = 101;
    private static final int WEEKLY_CREATE = 10001;
    private static final int WEEKLY_TEMPLATE = 10002;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WEEKLY_CREATE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        Intent detail = new Intent(mActivity, WeeklyDetailListActivity.class);
                        detail.setAction("my_weekly");
                        detail.putExtra("groupId", mGroupId);
                        detail.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(detail);
                        finish();
                    }else{
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case WEEKLY_TEMPLATE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        List<WeeklyTemplate> templates = (List < WeeklyTemplate >) msg.obj;
                        for (int i = 0;i<templates.size();i++){
                            WeeklyTemplate weeklyTemplate = templates.get(i);
                            if (weeklyTemplate.getIs_default() == 1){
                                ArrayList<String> template = weeklyTemplate.getFields();
                                mData.clear();
                                for (int k = 0;k<template.size();k++){
                                    mData.add(new WeeklyEditBean(template.get(k),""));
                                }
                                mTemplateId = weeklyTemplate.get_id();
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }else{
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.weekly_create_layout);
    }

    @Override
    public void initListener() {
        mTvTime.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        mLayoutBack.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mLayoutScroll.smoothScrollTo(0,20);
        mTvRight.setText("发布");
        mTvTitle.setText("新建周报");

        mAdapter = new WeeklyEditAdapter();
        mListView.setAdapter(mAdapter);

        mData = new ArrayList<WeeklyEditBean>();
        mEditData = (WeeklyDetailListData) getIntent().getSerializableExtra("weeklyDetailData");
        if (mEditData != null){
            flag = 2;
            mGroupId = mEditData.groupId;
            mWeeklyId = mEditData.weeklyId;
            mSelectDate = new WeeklyDateBean();
            mSelectDate.setWeekCount(Integer.parseInt(mEditData.weeklyCount));
            SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
            Date fristDate = WeekUtil.getWeekDateByCount(Integer.parseInt(mEditData.weeklyYear), Integer.parseInt(mEditData.weeklyMonth), Integer.parseInt(mEditData.weeklyCount));
            mFristDate = fristDate.getTime()/1000;
            String frist = sdf.format(WeekUtil.getFirstDayOfWeek(fristDate));
            String last = sdf.format(WeekUtil.getLastDayOfWeek(fristDate));
            String weeklyDate = String.format("（%s月第%s周）%s—%s",mEditData.weeklyMonth,mEditData.weeklyCount,frist,last);
            mSelectDate.setFirstDate(mFristDate);
            mSelectDate.setWeekCount(Integer.parseInt(mEditData.weeklyCount));
            mSelectDate.setDate(weeklyDate);
            mTvTime.setText(weeklyDate);

            try {
                JSONArray content = new JSONArray(mEditData.content);
                for (int i = 0; i < content.length(); i++) {
                    JSONObject item = content.getJSONObject(i);
                    WeeklyEditBean bean = new WeeklyEditBean();
                    bean.setTitle(item.getString("field"));
                    String value = item.getString("value");
                    if (!StringUtil.isEmpty(value)) {
                        bean.setContent(value);
                    }
                    mData.add(bean);
                }
                mAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else{
            flag = 1;
            mGroupId = getIntent().getStringExtra("groupId");
            mData.add(new WeeklyEditBean("上周总结",""));
            mData.add(new WeeklyEditBean("本周总结",""));
            mData.add(new WeeklyEditBean("协调帮助",""));
            getTemplateList();
        }



    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
        }
        mWaitDialog.show();

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.weekly_cr_tv_time:
                Intent mould = new Intent(mActivity,WeeklyDateActivity.class);
                mould.putExtra("fristDate",mFristDate);
                startActivityForResult(mould,SELECT_DATE);
                break;
            case R.id.title_tv_right:
                checkWeeklyContent();
                break;
            case R.id.title_ll_back:
                cancelAction();
                break;
        }
    }

    private void checkWeeklyContent(){
        if (mSelectDate == null){
            showShortToast("请选择时间");
            return;
        }
        JSONArray weekly = getWeeklyContent();
        if (!mIsOk){
            showShortToast("至少填写一项");
            return;
        }
        httpReqDlgShow();
        if (flag == 1){
            createWeekly(weekly.toString());
        }else{
            editWeekly(weekly.toString());
        }
    }

    /**
     * 获取内容
     *
     * @return
     */
    public JSONArray getWeeklyContent() {
        JSONArray array = new JSONArray();
        for (int i = 0; i < mListView.getChildCount(); i++) {
            RelativeLayout layout = (RelativeLayout) mListView.getChildAt(i);// 获得子item的layout
            EditText et = (EditText) layout.getChildAt(1);// 从layout中获得控件,根据其id
            // EditText et = (EditText) layout.getChildAt(1)//或者根据位置,在这我假设TextView在前，EditText在后
            String content = et.getText().toString().trim();
            if (!StringUtil.isEmpty(content)){
                mIsOk = true;
            }
            try {
                JSONObject object = new JSONObject();
                object.put("field",mData.get(i).getTitle());
                object.put("order",i + 1);
                object.put("value",et.getText().toString().trim());
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return array;
    }

    private void createWeekly(String content){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TEMPLATE_ID, mTemplateId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TIME, mSelectDate.getFirstDate() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_COUNT, mSelectDate.getWeekCount() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_CONTENT, content));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(WEEKLY_CREATE));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_NEW;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);

    }

    private void editWeekly(String content){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEKLY_ID, mWeeklyId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_TIME, mSelectDate.getFirstDate() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_COUNT, mSelectDate.getWeekCount() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_CONTENT, content));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(WEEKLY_CREATE));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_EDIT;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);

    }

    /**
     * 获取模板
     */
    private void getTemplateList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetWeeklyTemplateMsg message = new GetWeeklyTemplateMsg(mHandler.obtainMessage(WEEKLY_TEMPLATE));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_TEMPLATE_LIST;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
        httpReqDlgShow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == SELECT_DATE){
                mSelectDate = (WeeklyDateBean) data.getSerializableExtra("weekly_date");
                mFristDate = mSelectDate.getFirstDate();
                mTvTime.setText(mSelectDate.getDate());
                WeeklyMainActivity.isLoad = true;

            }
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        cancelAction();
    }

    private void cancelAction(){

        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(mActivity);
        dialogUtil.titleMsgBtnClick("提示","您是否确定退出撰写周报\n此周报未完成将不予保存","确定","取消");
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                finish();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });

    }

    class WeeklyEditAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mData == null?0:mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null){
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.weekly_cr_item_layout,null);
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.weekly_tv_title);
                holder.editContent = (EditText) convertView.findViewById(R.id.weekly_et_content);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            WeeklyEditBean weekly = mData.get(position);
            holder.title.setText(weekly.getTitle() + ":");
            if (!StringUtil.isEmpty(weekly.getContent())){
                holder.editContent.setText(weekly.getContent());
            }else{
                holder.editContent.setHint("请填写" + mData.get(position).getTitle());
            }
            return convertView;
        }

        class ViewHolder{
            private TextView title;
            private EditText editContent;
        }

    }
}
